package demo2;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * synchronized 和 lock比较
 * synchronized 自动释放锁、可重入锁非公平
 * lock必须手动释放锁、如果不释放会死锁、可重入锁非公平可以设置更改
 * @author aopmin
 * @since 2025/6/10
 */
public class Thread04 {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(ticket::sale, "A").start();
        new Thread(ticket::sale, "B").start();
    }

}

/**
 * 卖票小程序
 */
class Ticket {
    /**
     * 剩余票数
     */
    int num = 2;

    // ReentrantLock源码:
    // sync=new NonfairSync(); 默认非公平锁
    // FairSync 公平锁先来后到、NonfairSync 非公平锁可以插队
    // public ReentrantLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); }
    Lock lock = new ReentrantLock(false);

    public void sale() {
        lock.lock(); // 获取锁
        try {
            if (num > 0) {
                // if (Thread.currentThread().getName().equals("A")) {
                    TimeUnit.SECONDS.sleep(3);
                    String log = String.format("%s窗口正在卖票，现有：%s，剩余：%s", Thread.currentThread().getName(), num, --num);
                    System.out.println(log);
                // }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock(); // 避免死锁
        }
    }
}